package com.wtb.pub;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wtb.domain.DataCache;
import com.wtb.utils.DateUtils;

@SuppressWarnings("serial")
public class R2qServlet extends OpenAndClose {
	private static final Log log = LogFactory.getLog(R2qServlet.class);
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		super.doPost(request, response);
		String status = request.getParameter("status");
		if (status.equals("close")) {
			if (qqOauth.getQ2r().equals(CLOSE)) {  //已关闭微博到人人
				if (!closeTb()) {
					response.sendRedirect("error?err_code=1001");
					return;
				}
				response.sendRedirect("");
				return;
			}else {
				rrOauth.setR2q(CLOSE);
				try {
					rrDao.update(rrOauth);
					DataCache.rrmap.put(rrOauth.getUni(), rrOauth);
					session.setAttribute("r2q", "open");
				} catch (Exception e) {
					rrOauth.setR2q(OPEN);	//失败后还原标志
					log.error("关闭人人到微博同步错误：", e);
					response.sendRedirect("error?err_code=1001");
					return;
				}
			}
		}
		if (status.equals("open")) {
			if (rrOauth.getR2q()==null && qqOauth.getQ2r()==null) {  //没有此数据的信息
				if (!openTb(OPEN, CLOSE)) {
					response.sendRedirect("error?err_code=1000");
					return;
				}
			}else {    //有该账号的信息
				rrOauth.setR2q(OPEN);
				try {
					rrDao.update(rrOauth);
					DataCache.rrmap.put(rrOauth.getUni(), rrOauth);
					DataCache.rrlastTime.put(rrOauth.getUni(),DateUtils.createTime());
					session.setAttribute("r2q", "close");
				} catch (Exception e) {
					rrOauth.setR2q(CLOSE);   //失败后还原标志
					log.error("开启人人到微博同步错误：", e);
					response.sendRedirect("error?err_code=1000");
					return;
				}
			}
		}
		lastMap.put("qq", qqOauth);
		lastMap.put("rr", rrOauth);
		session.setAttribute("lastMap", lastMap);
		response.sendRedirect("");
	}
}
